package org.spiderflow.selenium.driver;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Keyboard;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.internal.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Set;


public class PhantomJsDriver implements WebDriver {

    String url;

    @Override
    public void get(String s) {
        this.url = s;
    }

    @Override
    public String getCurrentUrl() {
        return null;
    }

    @Override
    public String getTitle() {
        return null;
    }

    @Override
    public List<WebElement> findElements(By by) {
        return null;
    }

    @Override
    public WebElement findElement(By by) {
        return null;
    }


    @Override
    public String getPageSource() {
        try {
            return getParseredHtml(this.url);
        } catch (IOException e) {
            return "err";
        }
    }

    @Override
    public void close() {

    }

    @Override
    public void quit() {

    }

    @Override
    public Set<String> getWindowHandles() {
        return null;
    }

    @Override
    public String getWindowHandle() {
        return null;
    }

    @Override
    public TargetLocator switchTo() {
        return null;
    }

    @Override
    public Navigation navigate() {
        return null;
    }

    @Override
    public Options manage() {
        return new PhantomJsOptions();
    }

    // 调用phantomjs程序，并传入js文件，并通过流拿回需要的数据。
    public String getParseredHtml(String url) throws IOException {
        String exePath = System.getProperty("webdriver.phantomJs.driver");
        String jsPath = System.getProperty("webdriver.phantomJs.jsPath");
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec(exePath + " " + jsPath + " " + url);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
        StringBuffer sbf = new StringBuffer();
        String tmp = "";
        while ((tmp = bufferedReader.readLine()) != null) {
            sbf.append(tmp);
        }
        String orgHtml = sbf.toString();
        Document document = Jsoup.parse(orgHtml);
        return document.outerHtml();
    }


}
